package net.qhzw.vip.qiyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.qhzw.vip.qiyu.component.ServerConfig;
import net.qhzw.vip.qiyu.constant.SysConstants;
import net.qhzw.vip.qiyu.entity.*;
import net.qhzw.vip.qiyu.handler.MyException;
import net.qhzw.vip.qiyu.mapper.ContractMapper;
import net.qhzw.vip.qiyu.model.ContractFom;
import net.qhzw.vip.qiyu.model.ContractVo;
import net.qhzw.vip.qiyu.service.*;
import net.qhzw.vip.qiyu.util.BeanMapUtils;
import net.qhzw.vip.qiyu.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ContractServiceImpl extends ServiceImpl<ContractMapper, Contract> implements ContractService {


    @Autowired
    private DtsUserService dtsUserService;

    @Autowired
    private SysContractService sysContractService;


    @Autowired
    private SysCommunityService communityService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private DtsCarRentalService dtsCarRentalService;

    @Autowired
    private RepairCodeService repairCodeService;

    @Autowired
    private GuaranteeCompanyService guaranteeCompanyService;

    @Autowired
    private GuaranteeSiteService guaranteeSiteService;

    /***
     * 查看合同
     * @param userId
     * @return
     */
    @Override
    public ContractVo find(Long userId) {
        DtsUser dtsUser = dtsUserService.getById(userId);
        checkUser(dtsUser);
        ContractVo contractVo = new ContractVo();
        contractVo.setDtsUser(dtsUser);
        QueryWrapper<SysContract> queryWrapper = new QueryWrapper<>();
        queryWrapper.last("LIMIT 1");
        SysContract sysContract = sysContractService.getOne(queryWrapper);
        contractVo.setSysContract(sysContract);
        return contractVo;
    }

    /***
     * 根据站点id查询站点地址
     * @param communityId
     * @return
     */
    @Override
    public String findAddressById(String communityId) {
        return communityService.findAddressById(communityId);
    }

    @Override
    public Long addContract(ContractFom contractFom, HttpServletRequest request) {
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<Contract> queryWrapper = new LambdaQueryWrapper<Contract>()
                .eq(Contract::getUserId, userId)
                .eq(Contract::getStatus, 1);
        int count = count(queryWrapper);
//        if (count > 0) {
//            queryWrapper.last("ORDER BY created DESC LIMIT 1");
//            Contract contract = getOne(queryWrapper);
//            return contract.getId();
//        }
        String authorization = request.getHeader("Authorization");
        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", authorization);
        //headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<ContractFom> entity = new HttpEntity<>(contractFom, headers);
        String url = serverConfig.getUrl();
        Map<String, Object> param = BeanMapUtils.beanToMap(contractFom);
        url += "/contract/show?communityId=" + contractFom.getCommunityId() + "&terminationDate=" + contractFom.getTerminationDate() + "&sign=" + contractFom.getSign();
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class, param);
        String html = responseEntity.getBody();
        Contract contract = new Contract();
        long id = IdWorker.getId();
        contract.setId(id);
        contract.setUserId(SecurityUtils.getUserId());
        contract.setContent(html);
        contract.setCreated(new Date());
        boolean save = save(contract);
        if (save) {
            return id;
        }
        return null;
    }

    /***
     * 分页查询提交的合同
     * @param page
     * @param keywords
     * @return
     */
    @Override
    public Page<Contract> findBYPage(Page<Contract> page, String keywords, Byte status) {
        page.addOrder(OrderItem.desc("created"));
        LambdaQueryWrapper<Contract> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(status != null, Contract::getStatus, status);
        if (!StringUtils.isEmpty(keywords)) {
            //根据关键词查询用户
            List<DtsUser> dtsUserList = dtsUserService.findListByKeywords(keywords);
            List<Long> idList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(dtsUserList)) {
                idList = dtsUserList.stream().map(DtsUser::getId).collect(Collectors.toList());
                queryWrapper.in(!CollectionUtils.isEmpty(dtsUserList), Contract::getUserId, idList);
            }
        }

        Page<Contract> contractPage = page(page, queryWrapper);
        List<Contract> records = contractPage.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            for (Contract record : records) {
                DtsUser dtsUser = dtsUserService.getById(record.getUserId());
                record.setDtsUser(dtsUser);
            }
        }
        return contractPage;
    }

    @Override
    public boolean addOrderId(long orderId, Long contractItemId) {
        Contract contract = new Contract();
        contract.setOrderId(orderId);
        contract.setId(contractItemId);
        return updateById(contract);
    }


    /***
     * 根据UserId查询
     * @param userId
     * @return
     */
    @Override
    public DtsUser findUserById(Long userId) {
        DtsUser dtsUser = dtsUserService.getById(userId);
        if (dtsUser == null) {
            throw new MyException("参数错误,根据用户id无效");
        }
        return dtsUser;
    }

    /***
     * 根据用户换电ID
     *  骑遇 用户换电ID 7位
     *  骑缘 用户换电ID 11位
     * @param batterySwapId
     * @return
     */
    @Override
    public SysContract getSysContractByBatterySwapId(String batterySwapId) {
        SysContract sysContract = null;
        if (batterySwapId.length() < 11) {
            sysContract = sysContractService.getOne(new LambdaQueryWrapper<SysContract>()
                    .eq(SysContract::getType, SysConstants.QIYU));
        } else {
            sysContract = sysContractService.getOne(new LambdaQueryWrapper<SysContract>()
                    .eq(SysContract::getType, SysConstants.QIYUAN));
        }
        return sysContract;
    }

    @Override
    public DtsCarRental findDtsCarRentalById(Long dtsCarRentalId) {
        DtsCarRental carRental = dtsCarRentalService.getById(dtsCarRentalId);
        if (carRental == null) {
            throw new MyException("参数错误,租车申请id无效");
        }
        return carRental;
    }


    /****
     * 根据id获取站点信息
     * @param communityId
     * @return
     */
    @Override
    public SysCommunity getCommunityById(Long communityId) {
        return communityService.getById(communityId);
    }


    /***
     * 根据id获取车辆信息
     * @param repairCodeId
     * @return
     */
    @Override
    public RepairCode getRepairCodeById(Long repairCodeId) {
        if (repairCodeId == null) {
            return null;
        }
        return repairCodeService.getById(repairCodeId);
    }


    /***
     * 根据ID获取担保公司
     * @param guaranteeCompanyId
     * @return
     */
    @Override
    public GuaranteeCompany getGuaranteeCompanyById(Long guaranteeCompanyId) {
        if (guaranteeCompanyId == null) {
            return null;
        }
        return guaranteeCompanyService.getById(guaranteeCompanyId);
    }


    /***
     * 获取担保站点
     * @param idCard
     * @return
     */
    @Override
    public GuaranteeSite getGuaranteeSiteByUserId(String idCard) {
        return guaranteeSiteService.getGuaranteeSiteByUserId(idCard);
    }


    public boolean isFloat(String str) {
        try {
            Float.parseFloat(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }


    /***
     * 校验用户
     * @param dtsUser
     */
    private void checkUser(DtsUser dtsUser) {
        if (dtsUser == null) {
            throw new MyException(401, "登录信息已过期,请退出重新登录");
        }
        if (dtsUser.getAuthStatus().intValue() != 2) {
            throw new MyException(500, "实名未通过,暂不能租车");
        }
    }


}
